package com.hyb.config;

import com.hyb.Realm.MyRealm;
import com.hyb.shiro.JwtFilter;
import com.hyb.shiro.MyCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 *  shiro   配置类
 * </p>
 *
 * @author hyb
 * @since 2021-12-29
 */
@Configuration
public class ShiroConfig {

    @Autowired
    private MyRealm myRealm;

    @Autowired
    private MyCredentialsMatcher myCredentialsMatcher;



    @Bean
   public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        myRealm.setCredentialsMatcher(myCredentialsMatcher);

        manager.setRealm(myRealm);
        return manager;
    }

    @Bean
    public ShiroFilterFactoryBean getFilterFactoryBean(DefaultWebSecurityManager manager,JwtFilter jwtFilter){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(manager);
        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("jwt",jwtFilter);
        filterFactoryBean.setFilters(filterMap);
        Map<String,String> map = new LinkedHashMap<>();

        map.put("/swagger-ui.html**","anon");
        map.put("/v2/api-docs","anon");
        map.put("/swagger-resources/**","anon");
        map.put("/staff/test","anon");
        map.put("/**","jwt");
        filterFactoryBean.setFilterChainDefinitionMap(map);
        filterFactoryBean.setLoginUrl("/staff/login");
        return filterFactoryBean;
    }

    @Bean
    public JwtFilter getJwtFilter(){
        return new JwtFilter();
    }

    /**
     * 开启注释
     * @param securityManager
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        final AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
